<template>
  <div class="article-publish-container">
    <!-- 顶部标题区域 -->
    <div ref="headerRef" class="header-section">
      <!-- 页面标题 -->
      <div v-if="!loading" class="page-title">
        <h2>
          <IconifyIconOnline
            :icon="editMode ? 'ep:edit' : 'ep:document-add'"
            class="title-icon"
          />
          {{ editMode ? "编辑文章" : "发布文章" }}
        </h2>
        <div
          class="mode-badge"
          :class="{ 'edit-mode': editMode, 'create-mode': !editMode }"
        >
          {{ editMode ? "编辑模式" : "新建模式" }}
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-header">
        <el-skeleton animated>
          <template #template>
            <el-skeleton-item variant="h3" style="width: 200px" />
          </template>
        </el-skeleton>
      </div>

      <!-- 标题输入框 -->
      <div class="title-input-wrapper">
        <el-input
          v-model="articleForm.title"
          placeholder="请输入文章标题..."
          size="large"
          class="title-input"
          maxlength="200"
          show-word-limit
          clearable
          :disabled="loading"
        />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 编辑器区域 -->
      <div class="editor-section">
        <!-- 编辑器切换按钮 -->
        <div class="editor-switch-bar">
          <div class="switch-buttons">
            <el-button-group>
              <el-button
                :type="editorType === 'markdown' ? 'primary' : 'default'"
                :icon="
                  editorType === 'markdown' ? 'ep:document' : 'ep:document'
                "
                size="small"
                @click="switchEditor('markdown')"
              >
                <IconifyIconOnline
                  icon="mdi:language-markdown"
                  style="margin-right: 4px"
                />
                Markdown
              </el-button>
              <el-button
                :type="editorType === 'richtext' ? 'primary' : 'default'"
                :icon="editorType === 'richtext' ? 'ep:edit' : 'ep:edit'"
                size="small"
                @click="switchEditor('richtext')"
              >
                <IconifyIconOnline
                  icon="material-symbols:format-text-overflow-rounded"
                  style="margin-right: 4px"
                />
                富文本
              </el-button>
            </el-button-group>
          </div>
          <div class="editor-info">
            <span class="current-mode"
              >当前模式：{{
                editorType === "markdown" ? "Markdown 编辑器" : "富文本编辑器"
              }}</span
            >
          </div>
        </div>

        <!-- 编辑器内容区域 - 独立容器确保全屏时不包含其他元素 -->
        <div class="editor-content">
          <!-- 编辑器独立容器 - 全屏时只包含编辑器本身 -->
          <div class="editor-wrapper">
            <!-- Markdown编辑器 -->
            <MdEditor
              v-if="editorType === 'markdown'"
              v-model="currentEditorContent"
              :height="editorHeight"
              :preview="true"
              :toolbars="toolbars"
              :theme="'light'"
              :preview-theme="'default'"
              :code-theme="'atom'"
              placeholder="开始写作吧... 支持 Markdown 语法"
              @on-upload-img="handleUploadImg"
              @on-save="handleSave"
              @onChange="handleMarkdownChange"
            />

            <!-- 富文本编辑器 -->
            <RichTextEditor
              v-else-if="editorType === 'richtext'"
              ref="richTextEditorRef"
              v-model="currentEditorContent"
              :height="editorHeight"
              placeholder="开始写作吧... 使用富文本编辑器"
              @change="handleRichTextChange"
            />
          </div>
        </div>
      </div>

      <!-- 设置面板 -->
      <div ref="settingsRef" class="settings-panel">
        <el-card class="settings-card" shadow="never">
          <template #header>
            <div class="card-header">
              <IconifyIconOnline icon="ep:setting" />
              <span>文章设置</span>
            </div>
          </template>

          <!-- 左侧列 -->
          <div class="left-column">
            <!-- 分类选择 -->
            <div class="setting-item">
              <label class="setting-label">分类</label>
              <el-select
                v-model="articleForm.categoryId"
                placeholder="请选择文章分类"
                style="width: 100%"
                filterable
                clearable
                popper-class="category-select-dropdown"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                  class="category-option-item"
                >
                  <div class="category-option">
                    <IconifyIconOnline
                      :icon="category.icon || 'ep:folder'"
                      class="category-icon"
                    />
                    <span class="category-name">{{ category.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>

            <!-- 标签选择 -->
            <div class="setting-item">
              <label class="setting-label">标签</label>

              <!-- 已选中的标签展示 -->
              <div v-if="selectedTags.length > 0" class="selected-tags-display">
                <el-tag
                  v-for="tag in selectedTags"
                  :key="tag.id"
                  closable
                  :style="{
                    backgroundColor: tag.color || '#1677ff',
                    borderColor: tag.color || '#1677ff',
                    color: '#ffffff'
                  }"
                  class="selected-tag-item"
                  @close="removeSelectedTag(tag.id)"
                >
                  {{ tag.name }}
                </el-tag>
              </div>

              <!-- 标签选择按钮 -->
              <el-popover
                v-model:visible="tagPopoverVisible"
                placement="bottom-start"
                :width="400"
                trigger="click"
                popper-class="tag-selector-popover"
              >
                <template #reference>
                  <el-button
                    class="tag-selector-button"
                    :style="{
                      background: '#ffffff',
                      color: '#555666',
                      border: '1px solid #d1d5db',
                      width: '100%'
                    }"
                  >
                    <IconifyIconOnline
                      icon="ep:price-tag"
                      class="button-icon"
                    />
                    <span class="button-text">
                      {{
                        selectedTags.length > 0
                          ? `已选择 ${selectedTags.length}/7 个标签`
                          : "选择标签（最多7个）"
                      }}
                    </span>
                  </el-button>
                </template>

                <!-- 标签选择器内容 -->
                <div class="tag-selector-content">
                  <!-- 搜索框 -->
                  <div class="tag-search">
                    <el-input
                      v-model="tagSearchKeyword"
                      placeholder="搜索标签..."
                      clearable
                    >
                      <template #prefix>
                        <IconifyIconOnline icon="ep:search" />
                      </template>
                    </el-input>
                  </div>

                  <!-- 热门标签区域 -->
                  <div
                    v-if="hotTags.length > 0 && !tagSearchKeyword"
                    class="hot-tags-section"
                  >
                    <div class="section-title">
                      <IconifyIconOnline icon="ep:hot-water" />
                      <span>热门标签</span>
                    </div>
                    <div class="tags-container">
                      <div
                        v-for="tag in hotTags.slice(0, 15)"
                        :key="tag.id"
                        class="tag-button"
                        :class="{
                          'tag-selected': isTagSelected(tag.id),
                          'tag-disabled':
                            !isTagSelected(tag.id) && selectedTags.length >= 7
                        }"
                        :style="{
                          '--tag-color': tag.color || '#1677ff',
                          backgroundColor: isTagSelected(tag.id)
                            ? tag.color || '#1677ff'
                            : `${tag.color || '#1677ff'}15`,
                          borderColor: tag.color || '#1677ff',
                          color: isTagSelected(tag.id)
                            ? '#ffffff'
                            : tag.color || '#1677ff'
                        }"
                        @click="toggleTag(tag)"
                      >
                        {{ tag.name }}
                      </div>
                    </div>
                  </div>

                  <!-- 所有标签区域 -->
                  <div class="all-tags-section">
                    <div class="section-title">
                      <IconifyIconOnline icon="ep:collection-tag" />
                      <span>{{
                        tagSearchKeyword ? "搜索结果" : "所有标签"
                      }}</span>
                      <span class="tags-count">({{ displayTags.length }})</span>
                    </div>
                    <div
                      v-if="displayTags.length > 0"
                      class="tags-container scrollable"
                    >
                      <div
                        v-for="tag in displayTags"
                        :key="tag.id"
                        class="tag-button"
                        :class="{
                          'tag-selected': isTagSelected(tag.id),
                          'tag-disabled':
                            !isTagSelected(tag.id) && selectedTags.length >= 7
                        }"
                        :style="{
                          '--tag-color': tag.color || '#1677ff',
                          backgroundColor: isTagSelected(tag.id)
                            ? tag.color || '#1677ff'
                            : `${tag.color || '#1677ff'}15`,
                          borderColor: tag.color || '#1677ff',
                          color: isTagSelected(tag.id)
                            ? '#ffffff'
                            : tag.color || '#1677ff'
                        }"
                        @click="toggleTag(tag)"
                      >
                        {{ tag.name }}
                      </div>
                    </div>
                    <div v-else class="no-tags">
                      <IconifyIconOnline icon="ep:warning" />
                      <span>{{
                        tagSearchKeyword ? "没有找到匹配的标签" : "暂无标签数据"
                      }}</span>
                    </div>
                  </div>

                  <!-- 底部操作按钮 -->
                  <div class="tag-actions">
                    <el-button size="small" @click="clearAllTags"
                      >清空</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="tagPopoverVisible = false"
                    >
                      确定（{{ selectedTags.length }}/7）
                    </el-button>
                  </div>
                </div>
              </el-popover>
            </div>

            <!-- 原创标识 -->
            <div class="setting-item">
              <label class="setting-label">原创标识</label>
              <el-radio-group v-model="articleForm.isOriginal">
                <el-radio :value="1">原创</el-radio>
                <el-radio :value="0">转载</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 右侧列 -->
          <div class="right-column">
            <!-- 封面图片（重构） -->
            <div class="setting-item cover-section">
              <div
                class="cover-card"
                style="
                  display: flex;
                  flex-direction: column;
                  overflow: hidden;
                  background: #fff !important;
                  border: 1px solid #e5e7eb !important;
                  border-radius: 12px !important;
                  box-shadow: 0 1px 3px rgb(0 0 0 / 10%) !important;
                "
              >
                <div
                  class="cover-header"
                  style="
                    display: flex !important;
                    flex-shrink: 0;
                    align-items: center !important;
                    justify-content: space-between !important;
                    padding: 16px !important;
                    border-bottom: 1px solid #f3f4f6 !important;
                  "
                >
                  <span
                    class="cover-title"
                    style="
                      margin: 0;
                      font-size: 12px !important;
                      font-weight: bold !important;
                      color: #1f2937 !important;
                    "
                  >
                    添加封面
                  </span>
                  <el-tooltip
                    :content="tooltipContent"
                    placement="top"
                    effect="light"
                    raw-content
                    popper-class="cover-help-tooltip"
                    :show-after="300"
                    :hide-after="100"
                  >
                    <button
                      class="help-icon"
                      type="button"
                      style="
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        width: 20px !important;
                        height: 20px !important;
                        font-size: 12px !important;
                        font-weight: bold !important;
                        line-height: 1;
                        color: #6b7280 !important;
                        cursor: pointer !important;
                        background: #f3f4f6 !important;
                        border: 1px solid #d1d5db !important;
                        border-radius: 50% !important;
                        transition: all 0.2s ease !important;
                      "
                      @mouseenter="
                        $event.target.style.background = '#e5e7eb';
                        $event.target.style.color = '#374151';
                      "
                      @mouseleave="
                        $event.target.style.background = '#f3f4f6';
                        $event.target.style.color = '#6b7280';
                      "
                    >
                      ?
                    </button>
                  </el-tooltip>
                </div>
                <div
                  class="cover-body"
                  :class="{ 'drag-over': isDragOver }"
                  :style="{
                    flex: 1,
                    position: 'relative',
                    minHeight: '120px',
                    cursor: 'pointer',
                    transition: 'all 0.2s ease',
                    background: isDragOver ? '#f0f9ff' : 'transparent'
                  }"
                  @dragover.prevent="onDragOver"
                  @dragleave.prevent="onDragLeave"
                  @drop.prevent="onDrop"
                >
                  <input
                    ref="coverInputRef"
                    class="hidden-file"
                    type="file"
                    accept="image/*"
                    style="
                      position: absolute !important;
                      top: -9999px !important;
                      left: -9999px !important;
                      pointer-events: none !important;
                      opacity: 0 !important;
                    "
                    @change="onFileChange"
                  />

                  <!-- 空状态：点击或拖拽上传 -->
                  <div
                    v-if="!articleForm.coverImage"
                    class="empty-state"
                    style="
                      display: flex !important;
                      align-items: center !important;
                      justify-content: center !important;
                      height: 100% !important;
                      min-height: 120px !important;
                      padding: 20px !important;
                      font-size: 14px !important;
                      color: #6b7280 !important;
                      text-align: center !important;
                      transition: color 0.2s ease !important;
                    "
                    @click="triggerSelect"
                    @mouseenter="$event.target.style.color = '#374151'"
                    @mouseleave="$event.target.style.color = '#6b7280'"
                  >
                    <div class="empty-text">点击或拖拽上传图片</div>
                  </div>

                  <!-- 预览状态 -->
                  <div
                    v-else
                    class="preview-wrapper"
                    style="
                      position: relative !important;
                      width: 100% !important;
                      height: 100% !important;
                      min-height: 120px !important;
                    "
                    @mouseenter="previewHover = true"
                    @mouseleave="previewHover = false"
                  >
                    <img
                      :src="articleForm.coverImage"
                      class="preview-image"
                      style="
                        display: block !important;
                        width: 100% !important;
                        height: 100% !important;
                        min-height: 120px !important;
                        object-fit: cover !important;
                        border-radius: 0 !important;
                      "
                      @error="handleCoverError"
                    />
                    <button
                      v-show="previewHover"
                      type="button"
                      class="close-btn"
                      style="
                        position: absolute !important;
                        top: 8px !important;
                        right: 8px !important;
                        z-index: 10 !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        width: 24px !important;
                        height: 24px !important;
                        font-size: 16px !important;
                        font-weight: bold !important;
                        line-height: 1;
                        color: white !important;
                        cursor: pointer !important;
                        background: rgb(0 0 0 / 60%) !important;
                        border: none !important;
                        border-radius: 50% !important;
                        transition: all 0.2s ease !important;
                      "
                      @click="resetCover"
                      @mouseenter="
                        $event.target.style.background = 'rgba(0, 0, 0, 0.8)';
                        $event.target.style.transform = 'scale(1.1)';
                      "
                      @mouseleave="
                        $event.target.style.background = 'rgba(0, 0, 0, 0.6)';
                        $event.target.style.transform = 'scale(1)';
                      "
                    >
                      ×
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 文章摘要 -->
            <div class="setting-item summary-section">
              <label class="setting-label">摘要</label>
              <el-input
                v-model="articleForm.summary"
                type="textarea"
                placeholder="文章摘要（可选，留空将自动生成）"
                :rows="4"
                maxlength="500"
                show-word-limit
                class="summary-textarea"
              />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div ref="actionRef" class="action-buttons">
      <div class="button-group">
        <!-- 编辑模式下的按钮 -->
        <template v-if="editMode">
          <el-button size="large" @click="handleCancel"> 取消 </el-button>
          <el-button
            type="primary"
            size="large"
            :loading="updating"
            @click="handleUpdate"
          >
            更新文章
          </el-button>
        </template>

        <!-- 新建模式下的按钮 -->
        <template v-else>
          <el-button size="large" @click="handleCancel"> 取消 </el-button>
          <el-button
            type="info"
            size="large"
            :loading="saving"
            @click="handleSaveDraft"
          >
            保存草稿
          </el-button>
          <el-button
            type="primary"
            size="large"
            :loading="publishing"
            @click="handlePublish"
          >
            立即发布
          </el-button>
        </template>
      </div>
    </div>

    <!-- 图片裁剪对话框 -->
    <ImageCropDialog
      v-model:visible="cropDialogVisible"
      :image-src="selectedImageForCrop"
      @confirm="handleCropConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  nextTick
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { IconifyIconOnline } from "@/components/ReIcon";
import ImageCropDialog from "@/components/ImageCropDialog.vue";
import RichTextEditor from "@/components/RichTextEditor.vue";
import {
  smartContentConvert,
  isHtmlContent,
  isMarkdownContent
} from "@/utils/contentConverter";
import {
  createArticleApi,
  updateArticleApi,
  getMyArticleDetailApi,
  uploadArticleCoverApi,
  uploadGeneralImagesApi,
  type CreateArticleRequest,
  type UpdateArticleRequest,
  type ArticlePublishResponse,
  type UnifiedFileUploadResponse
} from "@/api/user-article";
import { EditorType } from "@/constants/article";
import { getCategories, type Category } from "@/api/home";
import {
  searchTagsApi,
  getHotTagsApi,
  getAllTagsApi,
  type SimpleTagInfo
} from "@/api/article-tag";

defineOptions({
  name: "ArticlePublish"
});

// 路由和状态
const router = useRouter();
const route = useRoute();
const editorRef = ref();
const saving = ref(false);
const publishing = ref(false);
const updating = ref(false); // 更新状态

// 编辑模式相关状态
const editMode = ref(false); // 是否为编辑模式
const articleId = ref<number | null>(null); // 编辑的文章ID
const loading = ref(false); // 加载中状态

// md-editor-v3 工具栏配置
const toolbars = [
  "bold",
  "underline",
  "italic",
  "-",
  "title",
  "strikeThrough",
  "sub",
  "sup",
  "quote",
  "unorderedList",
  "orderedList",
  "task",
  "-",
  "codeRow",
  "code",
  "link",
  "image",
  "table",
  "mermaid",
  "katex",
  "-",
  "revoke",
  "next",
  "save",
  "=",
  "pageFullscreen",
  "fullscreen",
  "preview",
  "previewOnly",
  "htmlPreview",
  "catalog"
];

// 表单数据
const articleForm = reactive<CreateArticleRequest>({
  title: "",
  summary: "",
  content: "",
  editorTypes: EditorType.MARKDOWN, // 默认使用Markdown编辑器
  coverImage: "",
  categoryId: null as number | null,
  tagIds: [],
  isOriginal: 1,
  publishNow: true
});

// 分类和标签数据
const categories = ref<Category[]>([]);
const hotTags = ref<SimpleTagInfo[]>([]);
const searchTags = ref<SimpleTagInfo[]>([]);
const allTags = ref<SimpleTagInfo[]>([]);
const tagLoading = ref(false);

// 标签选择器相关状态
const tagPopoverVisible = ref(false);
const tagSearchKeyword = ref("");
const selectedTags = ref<SimpleTagInfo[]>([]);
const displayTags = computed(() => {
  if (tagSearchKeyword.value) {
    return allTags.value.filter(tag =>
      tag.name.toLowerCase().includes(tagSearchKeyword.value.toLowerCase())
    );
  }
  return allTags.value;
});

// 布局元素引用与编辑器高度
const headerRef = ref<HTMLElement | null>(null);
const settingsRef = ref<HTMLElement | null>(null);
const actionRef = ref<HTMLElement | null>(null);
const editorHeight = ref(600);

// 封面上传相关状态
const coverInputRef = ref<HTMLInputElement | null>(null);
const previewHover = ref(false);
const isDragOver = ref(false);
// 图片裁剪相关状态
const cropDialogVisible = ref(false);
const selectedImageForCrop = ref("");
// 编辑器类型相关状态
const editorType = ref<"markdown" | "richtext">("markdown"); // 默认使Markdown编辑器
const richTextEditorRef = ref();
// 双内容存储 - 分别存储Markdown和HTML版本
const contentStorage = reactive({
  markdown: "", // Markdown格式内容
  html: "", // HTML格式内容
  lastEditedBy: "markdown" as "markdown" | "richtext", // 最后修改的编辑器类型
  originalMarkdown: "", // 原始Markdown内容，用于保护
  originalHtml: "", // 原始HTML内容，用于保护
  isConverted: {
    // 记录内容是否是转换而来
    markdown: false,
    html: false
  }
});

// 当前编辑器内容的计算属性
const currentEditorContent = computed({
  get: () => {
    return editorType.value === "markdown"
      ? contentStorage.markdown
      : contentStorage.html;
  },
  set: (value: string) => {
    if (editorType.value === "markdown") {
      contentStorage.markdown = value;
      contentStorage.lastEditedBy = "markdown";
    } else {
      contentStorage.html = value;
      contentStorage.lastEditedBy = "richtext";
    }
    // 更新文章表单的content字段
    articleForm.content = value;
  }
});
// 优化的工具提示内容
const tooltipContent = computed(() => {
  return `
    <div style="
      line-height: 1.5;
      font-size: 13px;
      color: #374151;
      max-width: 280px;
      padding: 2px;
    ">
      <div style="
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 8px;
        font-size: 14px;
      ">
        🖼️ 封面图片上传说明
      </div>
      
      <div style="margin-bottom: 6px;">
        <span style="
          color: #059669;
          font-weight: 500;
          font-size: 12px;
          background: #ecfdf5;
          padding: 2px 6px;
          border-radius: 4px;
          margin-right: 4px;
        ">建议尺寸</span>
        <span>1200×600 像素</span>
      </div>
      
      <div style="margin-bottom: 6px;">
        <span style="
          color: #dc2626;
          font-weight: 500;
          font-size: 12px;
          background: #fef2f2;
          padding: 2px 6px;
          border-radius: 4px;
          margin-right: 4px;
        ">大小限制</span>
        <span>不超过 2MB</span>
      </div>
      
      <div style="margin-bottom: 6px;">
        <span style="
          color: #2563eb;
          font-weight: 500;
          font-size: 12px;
          background: #eff6ff;
          padding: 2px 6px;
          border-radius: 4px;
          margin-right: 4px;
        ">支持格式</span>
        <span>JPG、PNG、GIF、WEBP</span>
      </div>
      
      <div style="
        margin-top: 8px;
        padding-top: 6px;
        border-top: 1px solid #e5e7eb;
        font-size: 12px;
        color: #6b7280;
        font-style: italic;
      ">
        ✨ 封面将显示在文章顶部，作为内容的代表性图片
      </div>
    </div>
  `;
});

// 计算编辑器高度（视口高度减去头部、设置、底部按钮与间距）
const computeEditorHeight = () => {
  const headerH = headerRef.value?.offsetHeight || 0;
  const settingsH = settingsRef.value?.offsetHeight || 0;
  const actionH = 100; // 固定底部按钮栏高度（包含padding）
  const viewportH = window.innerHeight || document.documentElement.clientHeight;
  const padding = 48; // 顶部和底部安全边距
  const gaps = 24 + 24; // 各区块间距
  const calc = viewportH - headerH - settingsH - actionH - padding - gaps;
  editorHeight.value = Math.max(400, calc);
};

// 加载所有标签（ALLTAGS API）
const loadAllTags = async () => {
  try {
    const res = await getAllTagsApi();
    if (res?.code === 200 && Array.isArray(res.data)) {
      allTags.value = res.data;
    } else {
      allTags.value = [];
    }
  } catch (e) {
    console.error("加载所有标签失败:", e);
    allTags.value = [];
  }
};

// 刷新热门标签
const refreshHotTags = async () => {
  try {
    const res = await getHotTagsApi(20);
    if (res?.code === 200 && Array.isArray(res.data)) {
      hotTags.value = res.data;
    } else {
      hotTags.value = [];
    }
  } catch (error) {
    console.error("刷新热门标签失败:", error);
    hotTags.value = [];
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await getCategories();
    if (response?.code === 200 && Array.isArray(response.data)) {
      categories.value = response.data as Category[];
      console.log("✅ 分类加载成功，共", categories.value.length, "个分类");
    } else {
      console.warn("⚠️ 分类接口返回异常:", response);
      categories.value = [];
    }
  } catch (error) {
    console.error("❌ 加载分类失败:", error);
    ElMessage.error("加载分类失败");
    categories.value = [];
  }
};

// 处理全屏状态变化
const handleFullscreenChange = () => {
  const isFullscreen = !!(
    document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement
  );

  // 如果退出全屏，重新计算编辑器高度
  if (!isFullscreen) {
    setTimeout(() => {
      computeEditorHeight();
      // 移除全屏状态标记
      document.body.classList.remove("editor-fullscreen-active");
    }, 100);
  } else {
    // 添加全屏状态标记
    document.body.classList.add("editor-fullscreen-active");
  }
};

// 监听全屏状态变化
const setupFullscreenListeners = () => {
  document.addEventListener("fullscreenchange", handleFullscreenChange);
  document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
  document.addEventListener("mozfullscreenchange", handleFullscreenChange);
  document.addEventListener("MSFullscreenChange", handleFullscreenChange);
};

// 隐藏页面元素
const hidePageElements = () => {
  const elementsToHide = [
    ".lay-navbar",
    ".navbar",
    ".sidebar-container",
    ".action-buttons",
    ".settings-panel",
    ".header-section",
    ".layout-container",
    ".main-container",
    ".el-header",
    ".pure-layout",
    '[class*="navbar"]',
    '[class*="header"]',
    '[class*="nav-"]'
  ];

  elementsToHide.forEach(selector => {
    const elements = document.querySelectorAll(selector);
    elements.forEach(el => {
      const element = el as HTMLElement;
      element.style.display = "none";
      element.style.visibility = "hidden";
      element.style.opacity = "0";
      element.style.zIndex = "-1";
      element.style.position = "absolute";
      element.style.top = "-9999px";
    });
  });

  // 为body添加全屏标记
  document.body.classList.add("editor-fullscreen-active");

  // 为html元素也添加样式
  document.documentElement.style.overflow = "hidden";

  console.log("Page elements hidden for fullscreen mode");
};

// 显示页面元素
const showPageElements = () => {
  const elementsToShow = [
    ".lay-navbar",
    ".navbar",
    ".sidebar-container",
    ".action-buttons",
    ".settings-panel",
    ".header-section",
    ".layout-container",
    ".main-container",
    ".el-header",
    ".pure-layout",
    '[class*="navbar"]',
    '[class*="header"]',
    '[class*="nav-"]'
  ];

  elementsToShow.forEach(selector => {
    const elements = document.querySelectorAll(selector);
    elements.forEach(el => {
      const element = el as HTMLElement;
      element.style.display = "";
      element.style.visibility = "";
      element.style.opacity = "";
      element.style.zIndex = "";
      element.style.position = "";
      element.style.top = "";
    });
  });

  // 为body移除全屏标记
  document.body.classList.remove("editor-fullscreen-active");

  // 恢复html元素样式
  document.documentElement.style.overflow = "";

  console.log("Page elements restored from fullscreen mode");
};

// 监听MD编辑器的全屏状态变化
const observeEditorFullscreen = () => {
  // 只有在使用Markdown编辑器时才设置监听器
  if (editorType.value !== "markdown") {
    console.log(
      "跳过MD编辑器全屏监听器设置，当前编辑器类型:",
      editorType.value
    );
    return null;
  }

  let observer: MutationObserver | null = null;
  let retryCount = 0;
  const maxRetries = 5; // 最多重试5次

  const setupObserver = () => {
    // 先清理旧的观察器
    if (observer) {
      observer.disconnect();
    }

    observer = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        if (
          mutation.type === "attributes" &&
          (mutation.attributeName === "class" ||
            mutation.attributeName === "data-fullscreen")
        ) {
          const target = mutation.target as HTMLElement;
          const hasFullscreenClass =
            target.classList.contains("md-editor-fullscreen") ||
            target.classList.contains("md-editor-focus") ||
            target.classList.contains("fullscreen-mode") ||
            target.hasAttribute("data-fullscreen");

          console.log("Editor fullscreen state changed:", hasFullscreenClass);

          if (hasFullscreenClass) {
            // 编辑器进入全屏
            hidePageElements();
            // 强制设置编辑器优先级并移动到body
            setTimeout(() => {
              const editorElement = target.closest(".md-editor") as HTMLElement;
              if (editorElement && !editorElement.dataset.movedToBody) {
                // 记录原始父元素
                editorElement.dataset.originalParent =
                  editorElement.parentElement?.tagName || "";
                editorElement.dataset.movedToBody = "true";

                // 移动到body的直接子元素
                document.body.appendChild(editorElement);

                // 应用全屏样式
                editorElement.style.position = "fixed";
                editorElement.style.top = "0";
                editorElement.style.left = "0";
                editorElement.style.width = "100vw";
                editorElement.style.height = "100vh";
                editorElement.style.zIndex = "2147483647";
                editorElement.style.background = "#ffffff";
                editorElement.style.margin = "0";
                editorElement.style.padding = "0";
                editorElement.style.border = "none";
                editorElement.style.borderRadius = "0";
                editorElement.style.display = "flex";
                editorElement.style.flexDirection = "column";

                console.log(
                  "Moved editor to body and applied fullscreen styles"
                );
              }
            }, 10);
          } else if (!document.fullscreenElement) {
            // 编辑器退出全屏（且不是浏览器全屏）
            showPageElements();
            // 恢复编辑器位置和样式
            setTimeout(() => {
              const editorElement = document.querySelector(
                '.md-editor[data-moved-to-body="true"]'
              ) as HTMLElement;
              if (editorElement) {
                // 找到原始容器
                const originalContainer =
                  document.querySelector(".editor-wrapper");
                if (originalContainer) {
                  // 移动回原始位置
                  originalContainer.appendChild(editorElement);
                }

                // 清理标记和样式
                delete editorElement.dataset.movedToBody;
                delete editorElement.dataset.originalParent;

                editorElement.style.position = "";
                editorElement.style.top = "";
                editorElement.style.left = "";
                editorElement.style.width = "";
                editorElement.style.height = "";
                editorElement.style.zIndex = "";
                editorElement.style.background = "";
                editorElement.style.margin = "";
                editorElement.style.padding = "";
                editorElement.style.border = "";
                editorElement.style.borderRadius = "";
                editorElement.style.display = "";
                editorElement.style.flexDirection = "";

                console.log("Restored editor to original position");
              }
            }, 10);
          }
        }
      });
    });

    // 查找编辑器元素
    const editorElement = document.querySelector(".md-editor");
    if (editorElement) {
      observer.observe(editorElement, {
        attributes: true,
        attributeFilter: ["class", "data-fullscreen"],
        subtree: false
      });
      console.log("MD编辑器全屏监听器设置成功");
    } else {
      retryCount++;
      if (retryCount <= maxRetries) {
        console.log(
          `MD编辑器元素未找到，正在重试 (${retryCount}/${maxRetries})...`
        );
        // 如果没有找到编辑器，1秒后重试
        setTimeout(setupObserver, 1000);
      } else {
        console.log("MD编辑器元素查找重试次数已达上限，停止重试");
      }
    }
  };

  setupObserver();
  return observer;
};

// 监听编辑器类型变化，重新设置监听器
let editorObserver: MutationObserver | null = null;
const reinitializeEditorObserver = () => {
  // 清理旧的监听器
  if (editorObserver) {
    editorObserver.disconnect();
    editorObserver = null;
  }

  // 延迟设置新的监听器，确保编辑器已完全加载
  setTimeout(() => {
    editorObserver = observeEditorFullscreen();
  }, 500);
};

// 监听 allTags 变化，同步 selectedTags
watch(
  () => allTags.value,
  newAllTags => {
    if (newAllTags.length > 0 && articleForm.tagIds.length > 0) {
      // 根据 articleForm.tagIds 更新 selectedTags
      selectedTags.value = newAllTags.filter(tag =>
        articleForm.tagIds.includes(tag.id)
      );
    }
  },
  { immediate: true }
);

// 加载文章数据用于编辑
const loadArticleData = async (id: number) => {
  try {
    loading.value = true;
    console.log(`加载文章数据: ${id}`);

    const response = await getMyArticleDetailApi(id);
    if (response.code === 200 && response.data) {
      const article = response.data;

      // 填充表单数据
      articleForm.title = article.title;
      articleForm.content = article.content;
      articleForm.summary = article.summary || "";

      // 处理编辑器类型字段，兼容旧数据
      if (article.editorTypes) {
        articleForm.editorTypes = article.editorTypes;
        console.log("✅ 使用文章原有的编辑器类型:", article.editorTypes);
      } else {
        // 兼容旧数据，默认使用Markdown
        articleForm.editorTypes = EditorType.MARKDOWN;
        console.log("🔄 兼容旧数据，设置为Markdown编辑器");
      }

      // 根据editorTypes设置编辑器类型
      editorType.value =
        articleForm.editorTypes === EditorType.RICH_TEXT
          ? "richtext"
          : "markdown";

      // 初始化内容存储 - 根据编辑器类型处理内容
      if (articleForm.editorTypes === EditorType.RICH_TEXT) {
        // 富文本编辑器：优先使用htmlContent字段，其次使用content字段
        const htmlContent = article.htmlContent || article.content || "";
        contentStorage.html = htmlContent;
        contentStorage.originalHtml = htmlContent;
        contentStorage.markdown = "";
        contentStorage.originalMarkdown = "";
        contentStorage.lastEditedBy = "richtext";
        contentStorage.isConverted.html = false;
        contentStorage.isConverted.markdown = false;
        console.log("✅ 初始化富文本编辑器内容:", htmlContent.length, "个字符");
      } else {
        // Markdown编辑器：使用content字段
        const markdownContent = article.content || "";
        contentStorage.markdown = markdownContent;
        contentStorage.originalMarkdown = markdownContent;
        contentStorage.html = "";
        contentStorage.originalHtml = "";
        contentStorage.lastEditedBy = "markdown";
        contentStorage.isConverted.markdown = false;
        contentStorage.isConverted.html = false;
        console.log(
          "✅ 初始化Markdown编辑器内容:",
          markdownContent.length,
          "个字符"
        );
      }

      // 处理封面图片路径
      const originalCoverUrl = article.coverImage || "";
      console.log("🖼️ 原始封面图片路径:", originalCoverUrl);

      const processedCoverUrl = processImageUrl(originalCoverUrl);
      console.log("✅ 处理后的封面图片URL:", processedCoverUrl);

      articleForm.coverImage = processedCoverUrl;

      articleForm.categoryId = article.category.id;
      articleForm.isOriginal = article.isOriginal;
      articleForm.tagIds = article.tags.map(tag => tag.id);

      // 设置编辑模式
      editMode.value = true;
      articleId.value = id;

      console.log("✅ 文章数据加载成功", article);
      ElMessage.success("文章数据加载成功");
    } else {
      throw new Error(response.message || "加载文章失败");
    }
  } catch (error) {
    console.error("❌ 加载文章数据失败:", error);
    ElMessage.error("加载文章失败，将转为新建模式");
    // 加载失败时转为新建模式
    editMode.value = false;
    articleId.value = null;
  } finally {
    loading.value = false;
  }
};

// 初始化路由参数
const initRouteParams = () => {
  const id = route.params.id || route.query.id;
  if (id) {
    const parsedId = parseInt(id as string, 10);
    if (parsedId > 0) {
      console.log("🔄 检测到文章ID，进入编辑模式:", parsedId);
      return parsedId;
    }
  }
  console.log("🆕 新建文章模式");
  return null;
};

// 初始化
onMounted(async () => {
  console.log("🚀 文章发布页面初始化开始...");

  try {
    // 检查路由参数
    const routeArticleId = initRouteParams();

    // 并行加载基础数据
    await Promise.all([loadCategories(), refreshHotTags(), loadAllTags()]);

    console.log("✅ 基础数据加载完成");
    console.log("分类数据:", categories.value);
    console.log("热门标签数据:", hotTags.value);
    console.log("所有标签数据:", allTags.value);

    // 如果有文章ID，加载文章数据
    if (routeArticleId) {
      await loadArticleData(routeArticleId);
    }

    // 初始化已选中的标签
    if (allTags.value.length > 0 && articleForm.tagIds.length > 0) {
      selectedTags.value = allTags.value.filter(tag =>
        articleForm.tagIds.includes(tag.id)
      );
    }
  } catch (error) {
    console.error("❌ 数据加载失败:", error);
    ElMessage.error("页面数据加载失败，请刷新重试");
  }

  await nextTick();
  computeEditorHeight();
  window.addEventListener("resize", computeEditorHeight);

  // 设置全屏监听器
  setupFullscreenListeners();

  // 设置编辑器全屏状态观察器
  setTimeout(() => {
    editorObserver = observeEditorFullscreen();
  }, 500); // 等待编辑器完全加载

  console.log("🎉 文章发布页面初始化完成");
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", computeEditorHeight);
  // 移除全屏监听器
  document.removeEventListener("fullscreenchange", handleFullscreenChange);
  document.removeEventListener(
    "webkitfullscreenchange",
    handleFullscreenChange
  );
  document.removeEventListener("mozfullscreenchange", handleFullscreenChange);
  document.removeEventListener("MSFullscreenChange", handleFullscreenChange);

  // 清理编辑器观察器
  if (editorObserver) {
    editorObserver.disconnect();
    editorObserver = null;
    console.log("✅ 已清理编辑器观察器");
  }
});

// 加载热门标签
const loadHotTags = async () => {
  try {
    const res = await getHotTagsApi(20);
    if (res?.code === 200 && Array.isArray(res.data)) {
      hotTags.value = res.data;
      // 初始化搜索结果为热门标签
      searchTags.value = res.data;
    } else {
      hotTags.value = [];
      searchTags.value = [];
    }
  } catch (error) {
    console.error("加载热门标签失败:", error);
    hotTags.value = [];
    searchTags.value = [];
  }
};

// 标签搜索
const handleTagSearch = async (keyword: string) => {
  if (!keyword) {
    searchTags.value = hotTags.value;
    return;
  }

  try {
    tagLoading.value = true;
    const res = await searchTagsApi(keyword, 20);
    if (res?.code === 200 && Array.isArray(res.data)) {
      searchTags.value = res.data;
    } else {
      searchTags.value = [];
    }
  } catch (error) {
    console.error("搜索标签失败:", error);
    searchTags.value = [];
  } finally {
    tagLoading.value = false;
  }
};

// 标签选择器相关方法

// 判断标签是否被选中
const isTagSelected = (tagId: number) => {
  return selectedTags.value.some(tag => tag.id === tagId);
};

// 切换标签选择状态（最多选择7个）
const toggleTag = (tag: SimpleTagInfo) => {
  const isSelected = isTagSelected(tag.id);

  if (isSelected) {
    // 移除标签
    selectedTags.value = selectedTags.value.filter(t => t.id !== tag.id);
    articleForm.tagIds = articleForm.tagIds.filter(id => id !== tag.id);
  } else {
    // 添加标签
    if (selectedTags.value.length >= 7) {
      ElMessage.warning("最多只能选择 7 个标签");
      return;
    }
    selectedTags.value.push(tag);
    articleForm.tagIds.push(tag.id);
  }
};

// 移除选中的标签
const removeSelectedTag = (tagId: number) => {
  selectedTags.value = selectedTags.value.filter(tag => tag.id !== tagId);
  articleForm.tagIds = articleForm.tagIds.filter(id => id !== tagId);
};

// 清空所有标签
const clearAllTags = () => {
  selectedTags.value = [];
  articleForm.tagIds = [];
};

// 统一处理图片URL的工具函数
const processImageUrl = (imageUrl: string): string => {
  if (!imageUrl) return "";

  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith("http")) {
    return imageUrl;
  }

  // 处理相对路径
  const baseUrl = "http://localhost:8081";

  if (imageUrl.startsWith("/files")) {
    // 统一上传接口返回的路径格式
    return `${baseUrl}${imageUrl}`;
  } else if (imageUrl.startsWith("/")) {
    // 其他以 / 开始的路径
    return `${baseUrl}${imageUrl}`;
  } else {
    // 相对路径，默认加上 /files 前缀
    return `${baseUrl}/files/${imageUrl}`;
  }
};

// md-editor-v3 事件处理
const handleUploadImg = async (
  files: File[],
  callback: (urls: string[]) => void
) => {
  try {
    console.log("📄 开始上传图片", files);

    // 使用统一文件上传接口的通用图片批量上传
    const response = await uploadGeneralImagesApi(files);

    if (response.code === 200 && response.data) {
      // 使用统一接口返回的 fileUrl 字段，并处理相对路径
      const urls = response.data.map(img => {
        const originalUrl = img.fileUrl;
        console.log("🖼️ 编辑器图片原始 URL:", originalUrl);

        const processedUrl = processImageUrl(originalUrl);
        console.log("✅ 编辑器图片处理后 URL:", processedUrl);

        return processedUrl;
      });
      console.log("✅ 所有图片上传成功", urls);

      callback(urls);

      // 更细致的成功消息
      const successCount = response.data.length;
      const totalCount = files.length;
      if (successCount === totalCount) {
        ElMessage.success(`成功上传 ${successCount} 张图片`);
      } else {
        ElMessage.warning(`上传完成：${successCount}/${totalCount} 张图片成功`);
      }
    } else {
      throw new Error(response.message || "图片上传失败");
    }
  } catch (error) {
    console.error("❌ 图片上传失败:", error);
    ElMessage.error("图片上传失败，请重试");

    // 传递空数组给回调，防止编辑器卡死
    callback([]);
  }
};

const handleSave = () => {
  // 保存草稿
  handleSaveDraft();
};

// 移除全屏监听逻辑，使用编辑器默认行为

// 上传前检查
const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 自定义封面图片上传
const handleCoverUpload = async (options: any) => {
  try {
    console.log("🎨 开始上传封面图片", options.file);

    // 使用统一文件上传接口的文章封面专用接口
    const response = await uploadArticleCoverApi(options.file);

    if (response.code === 200 && response.data) {
      // 使用统一接口返回的 fileUrl 字段
      const originalUploadUrl = response.data.fileUrl;
      console.log("🖼️ 上传成功原始 URL:", originalUploadUrl);

      const processedUploadUrl = processImageUrl(originalUploadUrl);
      articleForm.coverImage = processedUploadUrl;
      console.log("✅ 封面图片上传成功:", processedUploadUrl);
      ElMessage.success("封面图片上传成功!");

      // 调用成功回调
      options.onSuccess && options.onSuccess(response.data);
    } else {
      throw new Error(response.message || "上传失败");
    }
  } catch (error) {
    console.error("❌ 封面图片上传失败:", error);
    ElMessage.error("封面图片上传失败，请重试");

    // 调用失败回调
    options.onError && options.onError(error);
  }
};

// 上传成功回调(保留兼容性)
const handleCoverUploadSuccess = (response: any, file: any) => {
  // 这个方法现在由自定义上传方法处理，保留作为后备
  console.log("handleCoverUploadSuccess (fallback)", response);
};

// 上传失败回调
const handleCoverUploadError = (error: any) => {
  console.error("图片上传失败:", error);
  ElMessage.error("图片上传失败，请重试");
};

// 重构的封面上传组件相关方法
const triggerSelect = () => {
  coverInputRef.value?.click();
};

const resetCover = () => {
  articleForm.coverImage = "";
  previewHover.value = false;
  if (coverInputRef.value) {
    coverInputRef.value.value = "";
  }
};

const onDragOver = (e: DragEvent) => {
  e.preventDefault();
  isDragOver.value = true;
};

const onDragLeave = (e: DragEvent) => {
  e.preventDefault();
  isDragOver.value = false;
};

const onDrop = async (e: DragEvent) => {
  e.preventDefault();
  isDragOver.value = false;

  const files = e.dataTransfer?.files;
  if (files && files.length > 0) {
    await processFile(files[0]);
  }
};

const onFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  const files = target.files;
  if (files && files.length > 0) {
    await processFile(files[0]);
  }
};

const processFile = async (file: File) => {
  // 验证文件
  if (!beforeCoverUpload(file)) {
    return;
  }

  // 创建文件预览URL，显示裁剪对话框
  const imageUrl = URL.createObjectURL(file);
  selectedImageForCrop.value = imageUrl;
  cropDialogVisible.value = true;

  console.log("📷 准备裁剪图片:", file.name);
};

// 移除封面图片
const removeCoverImage = () => {
  articleForm.coverImage = "";
  ElMessage.success("封面图片已删除");
};

// 处理封面加载错误
const handleCoverError = () => {
  ElMessage.error("封面图片加载失败");
};

// 处理裁剪确认
const handleCropConfirm = async (croppedFile: File) => {
  try {
    console.log("🎨 开始上传裁剪后的封面图片", croppedFile);

    const response = await uploadArticleCoverApi(croppedFile);

    if (response.code === 200 && response.data) {
      const originalUploadUrl = response.data.fileUrl;
      console.log("🖼️ 上传成功原始 URL:", originalUploadUrl);

      const processedUploadUrl = processImageUrl(originalUploadUrl);
      articleForm.coverImage = processedUploadUrl;
      console.log("✅ 裁剪封面图片上传成功:", processedUploadUrl);
      ElMessage.success("封面图片裁剪并上传成功!");
    } else {
      throw new Error(response.message || "上传失败");
    }
  } catch (error) {
    console.error("❌ 裁剪封面图片上传失败:", error);
    ElMessage.error("封面图片上传失败，请重试");
  } finally {
    // 清理预览URL
    if (
      selectedImageForCrop.value &&
      selectedImageForCrop.value.startsWith("blob:")
    ) {
      URL.revokeObjectURL(selectedImageForCrop.value);
    }
    selectedImageForCrop.value = "";
    cropDialogVisible.value = false;
  }
};

// 编辑器切换方法
const switchEditor = (type: "markdown" | "richtext") => {
  if (type === editorType.value) return;

  console.log(`🔄 编辑器切换：${editorType.value} -> ${type}`);
  console.log("当前内容状态:", {
    markdown: contentStorage.markdown.length,
    html: contentStorage.html.length,
    lastEditedBy: contentStorage.lastEditedBy,
    isConverted: contentStorage.isConverted
  });

  // 保存当前编辑器的内容到对应的原始存储中
  if (editorType.value === "markdown" && currentEditorContent.value) {
    contentStorage.originalMarkdown = currentEditorContent.value;
    contentStorage.isConverted.markdown = false; // 标记为原始内容
  } else if (editorType.value === "richtext" && currentEditorContent.value) {
    contentStorage.originalHtml = currentEditorContent.value;
    contentStorage.isConverted.html = false; // 标记为原始内容
  }

  // 检查目标格式是否已存在原始内容
  let targetContent = "";

  if (type === "markdown") {
    // 切换到Markdown：优先使用原始Markdown，其次使用当前Markdown，最后转换HTML
    if (
      contentStorage.originalMarkdown &&
      !contentStorage.isConverted.markdown
    ) {
      targetContent = contentStorage.originalMarkdown;
      console.log("✅ 使用原始Markdown内容");
    } else if (contentStorage.markdown) {
      targetContent = contentStorage.markdown;
      console.log("✅ 使用当前Markdown内容");
    } else if (contentStorage.html || contentStorage.originalHtml) {
      // 从HTML转换
      const sourceHtml = contentStorage.originalHtml || contentStorage.html;
      try {
        targetContent = smartContentConvert(sourceHtml, "markdown");
        contentStorage.isConverted.markdown = true; // 标记为转换内容
        console.log(
          "✅ HTML→Markdown转换成功:",
          targetContent.length,
          "个字符"
        );
        ElMessage.info("内容已从富文本格式转换为Markdown格式");
      } catch (error) {
        console.error("❌ HTML→Markdown转换失败:", error);
        ElMessage.warning("内容转换失败，将使用原始内容");
        targetContent = sourceHtml; // 降级使用原始HTML
      }
    }
    contentStorage.markdown = targetContent;
  } else {
    // 切换到富文本：优先使用原始HTML，其次使用当前HTML，最后转换Markdown
    if (contentStorage.originalHtml && !contentStorage.isConverted.html) {
      targetContent = contentStorage.originalHtml;
      console.log("✅ 使用原始HTML内容");
    } else if (contentStorage.html) {
      targetContent = contentStorage.html;
      console.log("✅ 使用当前HTML内容");
    } else if (contentStorage.markdown || contentStorage.originalMarkdown) {
      // 从Markdown转换
      const sourceMarkdown =
        contentStorage.originalMarkdown || contentStorage.markdown;
      try {
        targetContent = smartContentConvert(sourceMarkdown, "html");
        contentStorage.isConverted.html = true; // 标记为转换内容
        console.log(
          "✅ Markdown→HTML转换成功:",
          targetContent.length,
          "个字符"
        );
        ElMessage.info("内容已从Markdown格式转换为富文本格式");
      } catch (error) {
        console.error("❌ Markdown→HTML转换失败:", error);
        ElMessage.warning("内容转换失败，将使用原始内容");
        targetContent = sourceMarkdown; // 降级使用原始Markdown
      }
    }
    contentStorage.html = targetContent;
  }

  // 切换编辑器类型
  editorType.value = type;

  // 同步更新文章表单中的编辑器类型
  articleForm.editorTypes =
    type === "markdown" ? EditorType.MARKDOWN : EditorType.RICH_TEXT;

  // 更新文章表单的content字段为当前编辑器对应的内容
  articleForm.content = currentEditorContent.value;

  console.log("✅ 编辑器切换完成:", {
    editorType: type,
    editorTypes: articleForm.editorTypes,
    contentLength: articleForm.content.length,
    isConverted: contentStorage.isConverted
  });

  // 重新初始化编辑器监听器
  reinitializeEditorObserver();

  ElMessage.success(
    `已切换到${type === "markdown" ? "Markdown" : "富文本"}编辑器`
  );
};

// Markdown编辑器内容变化处理
const handleMarkdownChange = (content: string) => {
  console.log("Markdown编辑器内容变化:", content.length, "个字符");
  // 内容已经通过 currentEditorContent 计算属性自动同步到 contentStorage.markdown
  // 只有在内容真正发生变化时才重置转换标记
  if (content !== contentStorage.originalMarkdown) {
    // 如果内容与原始内容不同，表示用户进行了编辑
    contentStorage.originalMarkdown = content;
    contentStorage.isConverted.markdown = false; // 标记为原始内容

    // 只有在HTML是转换而来的情况下才清空
    if (contentStorage.isConverted.html) {
      contentStorage.html = ""; // 清空转换而来的HTML内容
      contentStorage.isConverted.html = false;
    }
  }
};

// 富文本编辑器内容变化处理
const handleRichTextChange = (content: string) => {
  console.log("富文本编辑器内容变化:", content.length, "个字符");
  // 内容已经通过 currentEditorContent 计算属性自动同步到 contentStorage.html
  // 只有在内容真正发生变化时才重置转换标记
  if (content !== contentStorage.originalHtml) {
    // 如果内容与原始内容不同，表示用户进行了编辑
    contentStorage.originalHtml = content;
    contentStorage.isConverted.html = false; // 标记为原始内容

    // 只有在Markdown是转换而来的情况下才清空
    if (contentStorage.isConverted.markdown) {
      contentStorage.markdown = ""; // 清空转换而来的Markdown内容
      contentStorage.isConverted.markdown = false;
    }
  }
};

// 初始化内容存储
const initializeContentStorage = (content: string) => {
  if (!content) {
    // 空内容，重置所有存储
    contentStorage.markdown = "";
    contentStorage.html = "";
    contentStorage.originalMarkdown = "";
    contentStorage.originalHtml = "";
    contentStorage.lastEditedBy = "markdown";
    contentStorage.isConverted.markdown = false;
    contentStorage.isConverted.html = false;
    return;
  }

  // 智能检测内容格式
  const isHtml = isHtmlContent(content);
  const isMarkdown = isMarkdownContent(content);

  console.log("🔍 内容格式检测:", {
    isHtml,
    isMarkdown,
    contentLength: content.length
  });

  if (isHtml && !isMarkdown) {
    // 纯HTML内容
    contentStorage.html = content;
    contentStorage.originalHtml = content; // 保存原始内容
    contentStorage.markdown = "";
    contentStorage.originalMarkdown = "";
    contentStorage.lastEditedBy = "richtext";
    contentStorage.isConverted.html = false; // 原始内容，非转换
    contentStorage.isConverted.markdown = false;
    editorType.value = "richtext"; // 设置默认编辑器
    articleForm.editorTypes = EditorType.RICH_TEXT; // 同步到表单
  } else {
    // Markdown内容或未检测到格式，默认作为Markdown处理
    contentStorage.markdown = content;
    contentStorage.originalMarkdown = content; // 保存原始内容
    contentStorage.html = "";
    contentStorage.originalHtml = "";
    contentStorage.lastEditedBy = "markdown";
    contentStorage.isConverted.markdown = false; // 原始内容，非转换
    contentStorage.isConverted.html = false;
    editorType.value = "markdown"; // 设置默认编辑器
    articleForm.editorTypes = EditorType.MARKDOWN; // 同步到表单
  }

  console.log("✅ 内容存储初始化完成:", {
    editorType: editorType.value,
    markdown: contentStorage.markdown.length,
    html: contentStorage.html.length,
    originalMarkdown: contentStorage.originalMarkdown.length,
    originalHtml: contentStorage.originalHtml.length,
    lastEditedBy: contentStorage.lastEditedBy,
    isConverted: contentStorage.isConverted
  });
};

// 初始化时设置空内容
initializeContentStorage("");

// 统一的错误处理
const handleApiError = (error: any, defaultMessage: string = "操作失败") => {
  let message = defaultMessage;

  if (error?.response?.data?.message) {
    message = error.response.data.message;
  } else if (error?.message) {
    message = error.message;
  } else if (typeof error === "string") {
    message = error;
  }

  // 特殊状态码处理
  if (error?.response?.status === 401) {
    message = "登录已过期，请重新登录";
    // 这里可以添加自动跳转到登录页的逻辑
  } else if (error?.response?.status === 403) {
    message = "没有权限执行此操作";
  } else if (error?.response?.status === 404) {
    message = "请求的资源不存在";
  } else if (error?.response?.status >= 500) {
    message = "服务器内部错误，请稍后重试";
  }

  console.error("❗ API错误:", {
    error,
    status: error?.response?.status,
    data: error?.response?.data,
    message
  });

  ElMessage.error(message);
  return message;
};

// 加载状态管理
const setLoadingState = (
  type: "saving" | "publishing" | "loading" | "updating",
  state: boolean
) => {
  switch (type) {
    case "saving":
      saving.value = state;
      break;
    case "publishing":
      publishing.value = state;
      break;
    case "loading":
      loading.value = state;
      break;
    case "updating":
      updating.value = state;
      break;
  }
};

// 验证表单
const validateForm = (): boolean => {
  // 验证标题
  if (!articleForm.title || !articleForm.title.trim()) {
    ElMessage.error("请输入文章标题");
    return false;
  }
  if (articleForm.title.trim().length > 200) {
    ElMessage.error("文章标题不能超过200个字符");
    return false;
  }

  // 验证内容
  if (!articleForm.content || !articleForm.content.trim()) {
    ElMessage.error("请输入文章内容");
    return false;
  }
  if (articleForm.content.trim().length < 10) {
    ElMessage.error("文章内容不能少于10个字符");
    return false;
  }

  // 验证分类
  if (!articleForm.categoryId || articleForm.categoryId <= 0) {
    ElMessage.error("请选择文章分类");
    return false;
  }

  // 验证摘要
  if (articleForm.summary && articleForm.summary.length > 500) {
    ElMessage.error("文章摘要不能超过500个字符");
    return false;
  }

  // 验证封面图片URL
  if (articleForm.coverImage && articleForm.coverImage.length > 500) {
    ElMessage.error("封面图片URL不能超过500个字符");
    return false;
  }

  // 验证标签数量
  if (articleForm.tagIds && articleForm.tagIds.length > 7) {
    ElMessage.error("最多只能选择7个标签");
    return false;
  }

  console.log("✅ 表单验证通过");
  return true;
};

// 保存草稿
const handleSaveDraft = async () => {
  if (!validateForm()) return;

  try {
    setLoadingState("saving", true);
    console.log("💾 开始保存草稿...", {
      editMode: editMode.value,
      articleId: articleId.value
    });

    let response;

    if (editMode.value && articleId.value) {
      // 编辑模式 - 更新文章
      const requestData = {
        id: articleId.value,
        ...articleForm,
        categoryId: articleForm.categoryId as number,
        publishNow: false
      };

      console.log("✏️ 更新文章为草稿", requestData);
      response = await updateArticleApi(requestData);
    } else {
      // 新建模式 - 创建文章
      const requestData: CreateArticleRequest = {
        ...articleForm,
        categoryId: articleForm.categoryId as number,
        publishNow: false
      };

      console.log("🆕 创建新草稿", requestData);
      response = await createArticleApi(requestData);
    }

    if (response.code === 200) {
      const successMsg = editMode.value ? "草稿更新成功" : "草稿保存成功";
      console.log("✅ " + successMsg, response.data);
      ElMessage.success(successMsg);

      // 跳转到我的文章页面
      router.push("/user/article/my");
    } else {
      throw new Error(response.message || "保存失败");
    }
  } catch (error) {
    handleApiError(error, editMode.value ? "更新草稿失败" : "保存草稿失败");
  } finally {
    setLoadingState("saving", false);
  }
};

// 立即发布
const handlePublish = async () => {
  if (!validateForm()) return;

  try {
    setLoadingState("publishing", true);
    console.log("🚀 开始发布文章...", {
      editMode: editMode.value,
      articleId: articleId.value
    });

    let response;

    if (editMode.value && articleId.value) {
      // 编辑模式 - 更新文章
      const requestData = {
        id: articleId.value,
        ...articleForm,
        categoryId: articleForm.categoryId as number,
        publishNow: true
      };

      console.log("✏️ 更新并发布文章", requestData);
      response = await updateArticleApi(requestData);
    } else {
      // 新建模式 - 创建文章
      const requestData: CreateArticleRequest = {
        ...articleForm,
        categoryId: articleForm.categoryId as number,
        publishNow: true
      };

      console.log("🆕 创建并发布文章", requestData);
      response = await createArticleApi(requestData);
    }

    if (response.code === 200) {
      const successMsg = editMode.value ? "文章更新并发布成功" : "文章发布成功";
      console.log("✅ " + successMsg, response.data);
      ElMessage.success(successMsg);

      // 跳转到我的文章页面
      router.push("/user/article/my");
    } else {
      throw new Error(response.message || "发布失败");
    }
  } catch (error) {
    handleApiError(error, editMode.value ? "文章更新失败" : "文章发布失败");
  } finally {
    setLoadingState("publishing", false);
  }
};

// 更新文章（编辑模式下使用）
const handleUpdate = async () => {
  if (!validateForm()) return;

  if (!editMode.value || !articleId.value) {
    ElMessage.error("当前不是编辑模式，无法更新");
    return;
  }

  try {
    setLoadingState("updating", true);
    console.log("🔄 开始更新文章...", {
      editMode: editMode.value,
      articleId: articleId.value
    });

    const requestData = {
      id: articleId.value,
      ...articleForm,
      categoryId: articleForm.categoryId as number
      // 编辑模式下保持原有的发布状态，不强制设置 publishNow
    };

    console.log("✏️ 更新文章", requestData);
    const response = await updateArticleApi(requestData);

    if (response.code === 200) {
      console.log("✅ 文章更新成功", response.data);
      ElMessage.success("文章更新成功");

      // 跳转到我的文章页面
      router.push("/user/article/my");
    } else {
      throw new Error(response.message || "更新失败");
    }
  } catch (error) {
    handleApiError(error, "文章更新失败");
  } finally {
    setLoadingState("updating", false);
  }
};

// 取消编辑
const handleCancel = async () => {
  if (articleForm.title || articleForm.content) {
    try {
      await ElMessageBox.confirm(
        "当前有未保存的内容，确定要离开吗？",
        "确认离开",
        {
          type: "warning"
        }
      );
    } catch {
      return;
    }
  }

  router.back();
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 1200px) {
  .article-publish-container {
    padding: 20px;

    .header-section .title-input-wrapper {
      max-width: 100%;
    }

    .main-content {
      max-width: 100%;
    }
  }
}

@media (width <= 768px) {
  .article-publish-container {
    padding: 12px 12px 90px;

    .header-section {
      margin-bottom: 16px;

      .title-input-wrapper .title-input :deep(.el-input__wrapper) {
        padding: 10px 12px;
        font-size: 16px;
      }
    }

    .main-content {
      flex-direction: column; // 移动端改为垂直布局
      gap: 16px;
      height: auto;

      .settings-panel {
        order: -1; // 设置面板放在上方
        width: 100%;

        .settings-card {
          height: auto;

          :deep(.el-card__body) {
            gap: 12px;
            padding: 12px;
          }
        }
      }

      .editor-section {
        min-height: 400px;

        .editor-content :deep(.md-editor) {
          .md-editor-input {
            padding: 12px;
            font-size: 13px;
          }
        }
      }
    }

    .action-buttons {
      padding: 12px 16px;

      .button-group {
        gap: 8px;

        .el-button {
          min-width: 90px;

          &.el-button--large {
            padding: 10px 16px;
            font-size: 13px;
          }
        }
      }
    }
  }
}

.article-publish-container {
  position: relative;
  min-height: 100vh;
  padding: 16px 16px 100px;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",
    Arial, sans-serif;
  background: #f9fafb;

  > * {
    position: relative;
    z-index: 1;
  }

  .header-section {
    margin-bottom: 20px;

    .page-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 8px;
      margin-bottom: 16px;

      h2 {
        display: flex;
        gap: 8px;
        align-items: center;
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;

        .title-icon {
          font-size: 20px;
          color: #3b82f6;
        }
      }

      .mode-badge {
        padding: 4px 12px;
        font-size: 12px;
        font-weight: 500;
        border: 1px solid;
        border-radius: 12px;

        &.create-mode {
          color: #059669;
          background: #ecfdf5;
          border-color: #a7f3d0;
        }

        &.edit-mode {
          color: #d97706;
          background: #fef3c7;
          border-color: #fcd34d;
        }
      }
    }

    .loading-header {
      padding: 0 8px;
      margin-bottom: 16px;
    }

    .title-input-wrapper {
      max-width: none;
      margin: 0;

      .title-input {
        :deep(.el-input__wrapper) {
          padding: 12px 16px;
          font-size: 18px;
          font-weight: 500;
          background: #fff;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          transition: all 0.2s ease;

          &:hover {
            border-color: #d1d5db;
          }

          &.is-focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgb(59 130 246 / 10%);
          }
        }

        :deep(.el-input__inner) {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.4;
          color: #1f2937;
          border: none;

          &::placeholder {
            font-weight: 400;
            color: #9ca3af;
          }
        }
      }
    }
  }

  .main-content {
    display: flex;
    flex-direction: row; // 改为水平布局
    gap: 20px;
    max-width: none; // 取消最大宽度限制
    height: calc(100vh - 180px); // 固定高度
    min-height: calc(100vh - 180px);
    margin: 0;

    .editor-section {
      position: relative;
      display: flex;
      flex: 1; // 编辑器占据更多空间
      flex-direction: column;
      min-width: 0; // 防止flex项目溢出
      overflow: hidden;
      background: #fff;
      border: 1px solid #e5e7eb;
      border-radius: 8px;

      // 编辑器切换栏样式
      .editor-switch-bar {
        display: flex;
        flex-shrink: 0;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        background: #f8f9fa;
        border-bottom: 1px solid #e8e8e8;

        .switch-buttons {
          display: flex;
          align-items: center;

          :deep(.el-button-group) {
            .el-button {
              display: flex;
              gap: 4px;
              align-items: center;
              padding: 8px 16px;
              font-size: 13px;
              border-radius: 4px;
              transition: all 0.2s ease;

              &:first-child {
                border-radius: 4px 0 0 4px;
              }

              &:last-child {
                border-radius: 0 4px 4px 0;
              }

              &.el-button--primary {
                font-weight: 600;
                color: #fff;
                background: #1890ff;
                border-color: #1890ff;

                &:hover {
                  background: #40a9ff;
                  border-color: #40a9ff;
                }
              }

              &.el-button--default {
                color: #666;
                background: #fff;
                border-color: #d9d9d9;

                &:hover {
                  color: #1890ff;
                  background: #f0f8ff;
                  border-color: #1890ff;
                }
              }

              .iconify {
                flex-shrink: 0;
                font-size: 14px;
              }
            }
          }
        }

        .editor-info {
          display: flex;
          align-items: center;

          .current-mode {
            padding: 4px 12px;
            font-size: 12px;
            font-weight: 500;
            color: #666;
            background: #e6f7ff;
            border: 1px solid #b3e0ff;
            border-radius: 12px;
          }
        }
      }

      .editor-content {
        position: relative;
        display: flex;
        flex: 1;
        flex-direction: column;
        overflow: hidden;

        .editor-wrapper {
          position: relative;
          flex: 1;
          overflow: hidden;
          isolation: isolate;
        }

        // md-editor-v3 样式覆盖 - 适配左右布局
        :deep(.md-editor) {
          display: flex;
          flex-direction: column;
          height: 100%;
          background: transparent;
          border: none;
          border-radius: 0;
          box-shadow: none;

          .md-editor-toolbar {
            flex-shrink: 0;
            padding: 8px 12px;
            font-size: 14px;
            background: #f9fafb;
            border-bottom: 1px solid #e5e7eb;
            border-radius: 0;
          }

          .md-editor-content {
            display: flex;
            flex: 1;
            background: #fff;
            border-radius: 0;
          }

          .md-editor-input-wrapper,
          .md-editor-preview-wrapper {
            flex: 1;
            background: #fff;
          }

          .md-editor-input {
            height: 100%;
            padding: 16px;
            font-family:
              "SF Pro Text",
              -apple-system,
              BlinkMacSystemFont,
              "Segoe UI",
              Roboto,
              sans-serif;
            font-size: 14px;
            line-height: 1.6;
            color: #374151;
          }

          .md-editor-preview {
            padding: 16px;
            font-size: 14px;
            line-height: 1.6;
          }

          // 全屏状态样式 - 解决被其他元素遵挡问题
          // 支持多种全屏状态类名
          &.md-editor-fullscreen,
          &.md-editor-focus,
          &[data-fullscreen="true"],
          &.fullscreen-mode {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 999999 !important; // 提高z-index优先级
            width: 100vw !important;
            height: 100vh !important;
            padding: 0 !important;
            margin: 0 !important;
            background: #fff !important;
            border: none !important;
            border-radius: 0 !important;
            box-shadow: none !important;
            transform: none !important;

            .md-editor-toolbar {
              position: relative !important;
              z-index: 999999 !important;
              padding: 12px 16px !important;
              font-size: 14px !important;
              background: #f9fafb !important;
              border-bottom: 1px solid #e5e7eb !important;
            }

            .md-editor-content {
              position: relative !important;
              z-index: 999999 !important;
              background: #fff !important;
            }

            .md-editor-input {
              z-index: 999999 !important;
              padding: 20px !important;
              font-size: 16px !important;
              line-height: 1.6 !important;
            }

            .md-editor-preview {
              z-index: 999999 !important;
              padding: 20px !important;
              font-size: 16px !important;
              line-height: 1.6 !important;
            }
          }
        }
      }
    }

    .settings-panel {
      flex-shrink: 0; // 不允许收缩
      order: 1; // 放在右侧
      width: 320px; // 固定宽度的右侧面板

      .settings-card {
        position: relative;
        height: 100%; // 占满高度
        overflow-y: auto; // 内容过多时可滚动
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 8px;

        /* 选中值文本不被挤压，超长省略显示（作用于选择框内的已选中展示） */
        :deep(.el-select .el-select__selected-item) {
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        :deep(.el-card__header) {
          display: none;
        }

        :deep(.el-card__body) {
          position: relative;
          display: flex;
          flex-direction: column;
          gap: 16px;
          padding: 16px;
        }

        // 单列垂直布局
        .left-column,
        .right-column {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .setting-item {
          position: relative;
          display: flex;
          flex-direction: column;
          gap: 8px;

          .setting-label {
            margin-bottom: 4px;
            font-size: 13px;
            font-weight: 500;
            color: #374151;
          }

          // 表单控件样式
          .el-select,
          .el-input,
          .el-radio-group {
            width: 100%;
          }

          // 热门标签区域
          .hot-tags-section {
            .hot-tags-list {
              display: flex;
              flex-wrap: wrap;
              gap: 10px;
              padding: 8px 0;
            }
          }

          // 摘要区域
          .summary-section {
            .summary-textarea {
              :deep(.el-textarea__inner) {
                min-height: 120px;
                font-size: 15px;
                line-height: 1.6;
                resize: vertical;
                border-radius: 12px;
              }
            }
          }

          // 简化表单控件样式
          :deep(.el-select),
          :deep(.el-input),
          :deep(.el-radio-group) {
            .el-select__wrapper,
            .el-input__wrapper {
              padding: 8px 12px;
              font-size: 13px;
              background: #fff;
              border: 1px solid #d1d5db;
              border-radius: 6px;
              transition: all 0.2s ease;

              &:hover {
                border-color: #9ca3af;
              }

              &.is-focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgb(59 130 246 / 10%);
              }
            }
          }

          // 分类选择器样式优化
          .category-option {
            display: flex;
            gap: 12px;
            align-items: center;
            width: 100%;
            min-height: 36px;
            padding: 8px 0;

            .category-icon {
              flex-shrink: 0;
              font-size: 18px;
              color: #606266;
            }

            .category-name {
              flex: 1;
              font-size: 14px;
              font-weight: 500;
              line-height: 1.4;
              color: #374151;
            }
          }

          .tag-option {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;

            .tag-count {
              margin-left: 8px;
              font-size: 12px;
              color: #909399;
            }
          }

          // 热门标签样式 - 支持动态颜色
          .hot-tag {
            padding: 6px 12px;
            margin: 2px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            border: 1px solid transparent;
            border-radius: 12px;
            transition: all 0.2s ease;

            &:hover {
              box-shadow: 0 3px 10px rgb(0 0 0 / 15%);
              filter: brightness(1.1);
              transform: translateY(-1px);
            }

            // 选中状态 - 使用后端颜色，白色文字
            &.tag-selected {
              font-weight: 600;
              color: #fff !important;
              box-shadow: 0 2px 6px rgb(0 0 0 / 20%);

              &:hover {
                box-shadow: 0 4px 12px rgb(0 0 0 / 25%);
                filter: brightness(1.1);
              }
            }

            // 未选中状态 - 浅色背景深色文字
            &.tag-unselected {
              color: #64748b;
              background: #f8fafc;
              border-color: #e2e8f0;

              &:hover {
                color: #475569;
                background: #e2e8f0;
              }
            }
          }

          // 标签选择器样式
          .selected-tags-display {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            min-height: 32px;
            padding: 8px;
            margin-bottom: 8px;
            background: #fafafa;
            border: 1px solid #e1e5e9;
            border-radius: 6px;

            .selected-tag-item {
              padding: 2px 6px;
              font-size: 12px;
              font-weight: 500;
              line-height: 1.4;
              border-radius: 4px;
              transition: all 0.2s ease;

              &:hover {
                box-shadow: 0 2px 6px rgb(0 0 0 / 15%);
                filter: brightness(0.9);
                transform: translateY(-1px);
              }
            }
          }

          /* 封面组件工具提示样式 */
          .cover-help-tooltip {
            max-width: 320px !important;

            .el-popper {
              padding: 12px !important;
              border: 1px solid #e5e7eb !important;
              border-radius: 8px !important;
              box-shadow: 0 4px 12px rgb(0 0 0 / 15%) !important;
            }

            .el-popper__arrow::before {
              border-top-color: #fff !important;
            }
          }

          .tag-selector-button {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 12px;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s ease;

            .button-icon {
              margin-right: 8px;
              font-size: 16px;
              color: #6b7280;
            }

            .button-text {
              flex: 1;
              text-align: left;
            }

            .arrow-icon {
              margin-left: 8px;
              font-size: 14px;
              color: #6b7280;
              transition: transform 0.2s ease;
            }

            &:hover {
              background: #f9fafb;
              border-color: #9ca3af;

              .button-icon,
              .arrow-icon {
                color: #374151;
              }
            }
          }
        }
      }
    }
  }

  .action-buttons {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1000;
    padding: 16px 24px;
    background: rgb(255 255 255 / 95%);
    border-top: 1px solid #e5e7eb;
    box-shadow: 0 -4px 16px rgb(0 0 0 / 8%);
    backdrop-filter: blur(10px);

    .button-group {
      display: flex;
      gap: 12px;
      justify-content: center;
      max-width: 1200px;
      margin: 0 auto;

      .el-button {
        min-width: 100px;
        font-weight: 500;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        transition: all 0.2s ease;

        &.el-button--large {
          padding: 10px 20px;
          font-size: 14px;
        }

        &.el-button--primary {
          color: white;
          background: #3b82f6;
          border-color: #3b82f6;

          &:hover {
            background: #2563eb;
            border-color: #2563eb;
          }
        }

        &.el-button--info {
          color: white;
          background: #6b7280;
          border-color: #6b7280;

          &:hover {
            background: #4b5563;
            border-color: #4b5563;
          }
        }

        &:not(.el-button--primary, .el-button--info) {
          color: #374151;
          background: #fff;
          border-color: #d1d5db;

          &:hover {
            background: #f9fafb;
            border-color: #9ca3af;
          }
        }
      }
    }
  }

  // 封面组件样式（新加）
  .article-publish-container {
    .settings-panel .settings-card .setting-item.cover-section {
      // 去除默认的 setting-item 边距
      gap: 0 !important;

      .cover-card {
        display: flex;
        flex-direction: column;
        overflow: hidden;
        background: #fff !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 12px !important;
        box-shadow: 0 1px 3px rgb(0 0 0 / 10%) !important;

        .cover-header {
          display: flex !important;
          flex-shrink: 0;
          align-items: center !important;
          justify-content: space-between !important;
          padding: 16px !important;
          border-bottom: 1px solid #f3f4f6 !important;

          .cover-title {
            margin: 0;
            font-size: 12px !important;
            font-weight: bold !important;
            color: #1f2937 !important;
          }

          .help-icon {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            width: 20px !important;
            height: 20px !important;
            font-size: 12px !important;
            font-weight: bold !important;
            line-height: 1;
            color: #6b7280 !important;
            cursor: pointer !important;
            background: #f3f4f6 !important;
            border: 1px solid #d1d5db !important;
            border-radius: 50% !important;
            transition: all 0.2s ease !important;

            &:hover {
              color: #374151 !important;
              background: #e5e7eb !important;
            }
          }
        }

        .cover-body {
          position: relative;
          flex: 1;
          min-height: 120px !important;
          cursor: pointer !important;
          transition: all 0.2s ease !important;

          &.drag-over {
            background: #f0f9ff !important;
          }

          .hidden-file {
            position: absolute !important;
            top: -9999px !important;
            left: -9999px !important;
            pointer-events: none !important;
            opacity: 0 !important;
          }

          .empty-state {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            height: 100% !important;
            min-height: 120px !important;
            padding: 20px !important;
            font-size: 14px !important;
            color: #6b7280 !important;
            text-align: center !important;
            transition: color 0.2s ease !important;

            .empty-text {
              font-size: 14px !important;
              color: #6b7280 !important;
            }

            &:hover {
              .empty-text {
                color: #374151 !important;
              }
            }
          }

          .preview-wrapper {
            position: relative !important;
            width: 100% !important;
            height: 100% !important;
            min-height: 120px !important;

            .preview-image {
              display: block !important;
              width: 100% !important;
              height: 100% !important;
              min-height: 120px !important;
              object-fit: cover !important;
              border-radius: 0 !important;
            }

            .close-btn {
              position: absolute !important;
              top: 8px !important;
              right: 8px !important;
              z-index: 10 !important;
              display: flex !important;
              align-items: center !important;
              justify-content: center !important;
              width: 24px !important;
              height: 24px !important;
              font-size: 16px !important;
              font-weight: bold !important;
              line-height: 1;
              color: white !important;
              cursor: pointer !important;
              background: rgb(0 0 0 / 60%) !important;
              border: none !important;
              border-radius: 50% !important;
              transition: all 0.2s ease !important;

              &:hover {
                background: rgb(0 0 0 / 80%) !important;
                transform: scale(1.1) !important;
              }
            }
          }
        }
      }
    }
  }
}

// 全局样式 - body全屏状态
body.editor-fullscreen-active {
  overflow: hidden !important;

  // 强制隐藏所有导航栏和布局元素
  .layout-container,
  .navbar,
  .lay-navbar,
  .main-container,
  .sidebar-container,
  .el-header,
  .pure-layout {
    z-index: -1 !important;
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
  }
}

// 全屏状态下的编辑器样式
body.editor-fullscreen-active .md-editor-fullscreen,
body.editor-fullscreen-active .md-editor-focus,
body.editor-fullscreen-active .md-editor[data-fullscreen="true"],
body.editor-fullscreen-active .fullscreen-mode,
.md-editor-fullscreen,
.md-editor-focus,
.md-editor[data-fullscreen="true"],
.fullscreen-mode {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 999999 !important;
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  margin: 0 !important;
  background: #fff !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  transform: none !important;
}

/* 最高优先级的全屏CSS样式 - 确保完全覆盖 */
.md-editor.md-editor-fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important; /* 最大的z-index值 */
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  margin: 0 !important;
  background: #fff !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
}

/* 标签选择器弹出框样式 */
.tag-selector-popover {
  .tag-selector-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
    max-height: 420px;

    .tag-search {
      .el-input {
        .el-input__wrapper {
          background: #f9fafb;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
        }
      }
    }

    .hot-tags-section,
    .all-tags-section {
      .section-title {
        display: flex;
        gap: 6px;
        align-items: center;
        margin-bottom: 6px;
        font-size: 13px;
        font-weight: 600;
        color: #374151;

        .iconify {
          font-size: 14px;
          color: #f59e0b;
        }

        .tags-count {
          font-size: 12px;
          font-weight: 400;
          color: #6b7280;
        }
      }

      .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;

        &.scrollable {
          max-height: 150px;
          padding-right: 4px;
          overflow-y: auto;
        }

        &::-webkit-scrollbar {
          width: 4px;
        }

        &::-webkit-scrollbar-track {
          background: #f1f5f9;
          border-radius: 2px;
        }

        &::-webkit-scrollbar-thumb {
          background: #cbd5e1;
          border-radius: 2px;

          &:hover {
            background: #94a3b8;
          }
        }

        .tag-button {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          min-height: 22px;
          padding: 2px 8px;
          margin: 0;
          font-size: 12px;
          font-weight: 400;
          line-height: 1.4;
          white-space: nowrap;
          cursor: pointer;
          user-select: none;
          border: 1px solid;
          border-radius: 4px;
          transition: all 0.2s ease;

          &:hover {
            box-shadow: 0 2px 6px rgb(0 0 0 / 10%);
            filter: brightness(0.95);
            transform: translateY(-1px);
          }

          &.tag-selected {
            font-weight: 500;
            box-shadow: 0 1px 4px rgb(0 0 0 / 15%);
          }

          &.tag-disabled {
            cursor: not-allowed;
            opacity: 0.4;

            &:hover {
              box-shadow: none;
              filter: none;
              transform: none;
            }
          }
        }
      }

      .no-tags {
        display: flex;
        gap: 8px;
        align-items: center;
        justify-content: center;
        padding: 20px;
        font-size: 12px;
        color: #9ca3af;

        .iconify {
          font-size: 16px;
        }
      }
    }

    .all-tags-section {
      .section-title .iconify {
        color: #6b7280;
      }
    }

    .tag-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 12px;
      border-top: 1px solid #f1f5f9;

      .el-button {
        font-size: 12px;
        font-weight: 500;
        border-radius: 6px;

        &.el-button--primary {
          background: #3b82f6;
          border-color: #3b82f6;

          &:hover {
            background: #2563eb;
            border-color: #2563eb;
          }
        }
      }
    }
  }
}

.md-editor.md-editor-focus {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important;
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  margin: 0 !important;
  background: #fff !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  transform: none !important;
}

.md-editor[data-fullscreen="true"] {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important;
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  margin: 0 !important;
  background: #fff !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  transform: none !important;
}

/* 全屏状态下的特殊处理 */
body.editor-fullscreen-active #app {
  display: none !important;
}

body.editor-fullscreen-active .layout-container {
  display: none !important;
}

body.editor-fullscreen-active .el-container {
  display: none !important;
}

/* 特殊处理：全屏编辑器直接附加到body */
body.editor-fullscreen-active .md-editor-fullscreen,
body.editor-fullscreen-active .md-editor-focus,
body.editor-fullscreen-active .md-editor[data-fullscreen="true"] {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important;
  display: flex !important;
  flex-direction: column !important;
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  margin: 0 !important;
  background: #fff !important;
  border: none !important;
  border-radius: 0 !important;
}

/* 全局分类选择器下拉框样式 */
.category-select-dropdown {
  .el-select-dropdown__item {
    min-height: 40px !important;
    padding: 8px 12px !important;

    &.hover {
      background-color: #f5f7fa !important;
    }

    &.selected {
      font-weight: 500 !important;
      color: #409eff !important;
    }
  }

  .category-option {
    display: flex !important;
    gap: 12px !important;
    align-items: center !important;
    width: 100% !important;

    .category-icon {
      flex-shrink: 0 !important;
      font-size: 18px !important;
      color: #606266 !important;
    }

    .category-name {
      flex: 1 !important;
      font-size: 14px !important;
      font-weight: 500 !important;
      line-height: 1.4 !important;
      color: #374151 !important;
    }
  }
}
</style>
